#include <webx/route.h>
#include <dbentity/T_XG_GROUP.h>

class ExportAccess : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(ExportAccess)

int ExportAccess::process()
{
	int res = 0;
	CT_XG_GROUP tab;
	sp<Session> session;
	string version = request->getHeadValue("If-None-Match");

	if (session = webx::GetLocaleSession("ACCESS"))
	{
		string etag = session->get("version");

		if (etag == version) throw Exception(XG_NOTCHANGED);

		response->setHeadValue("ETag", etag);

		out << session->get("content");

		return XG_OK;
	}

	typedef webx::AccessItem AccessItem;
	map<string, vector<AccessItem>> accessmap;

	if (!webx::LoadAccessMap(accessmap)) throw Exception(XG_SYSERR);
	
	JsonElement arr = json.addArray("list");

	for (auto& item : accessmap)
	{
		for (auto& tmp : item.second)
		{
			JsonElement data = arr[res++];

			data["path"] = item.first;
			data["param"] = tmp.getParamString();
			data["grouplist"] = tmp.getGroupString();
		}
	}

	string msg = json.toString();

	session = webx::GetLocaleSession("ACCESS", res > 0 ? 24 * 3600 : 5);
	version = MD5GetEncodeString(msg.c_str(), msg.length(), true).val;

	response->setHeadValue("ETag", version);

	json["code"] = res;

	if (session)
	{
		session->set("version", version);
		session->set("content", json.toString());
	}

	out << json;

	return XG_OK;
}